package com.zy.ems.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zy.ems.common.base.BaseController;
import com.zy.ems.common.exception.ApiException;
import com.zy.ems.common.exception.BaseErrorStatus;
import com.zy.ems.common.page.PaginationResult;
import com.zy.ems.common.util.DateUtil;
import com.zy.ems.common.util.JsonUtils;
import com.zy.ems.common.util.Md5Util;
import com.zy.ems.common.util.NetworkUtil;
import com.zy.ems.common.util.ResultTool;
import com.zy.ems.common.util.StringUtils;
import com.zy.ems.common.util.TokenUtils;
import com.zy.ems.model.UserEntity;
import com.zy.ems.service.UserService;
import com.zy.ems.utils.enums.StatusEnum;
import com.zy.ems.utils.enums.UserTypeEnum;
import com.zy.ems.utils.exceptions.UserCode;

@RestController
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUserList.json", method = RequestMethod.GET)
    public Object getUserList(HttpServletRequest request) {
        String q = request.getParameter("q");
        String start = request.getParameter("start");
        String size = request.getParameter("size");

        try {

            Map<String, Object> paramMap = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(q)) {
                paramMap = JsonUtils.readJson2Map(q, Object.class);
            }

            paramMap.put("size", size);
            paramMap.put("start", start);
            PaginationResult<UserEntity> data = this.userService
                    .getUserList(paramMap);

            return ResultTool.success(data);
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    /**
     * 用户登陆路
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/doLogin.json", method = RequestMethod.POST)
    public Object login(HttpServletRequest request) {
        String loginUser = StringUtils
                .parseStr(request.getParameter("loginUser"));

        try {

            if (StringUtils.isEmpty(loginUser)) {
                return ResultTool.error(UserCode.B_USER_2001);
            }

            Map<String, String> paramMap = JsonUtils.readJson2Map(loginUser,
                    String.class);

            if (paramMap == null) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            if (StringUtils.isEmpty(paramMap.get("username"),
                    paramMap.get("password"))) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            UserEntity user = this.userService.login(paramMap.get("username"));

            if (user == null) {
                return ResultTool.error(UserCode.B_USER_2001);
            }

            String password = Md5Util.getPasswordMd5(paramMap.get("password"),
                    user.getSalt());

            if (!password.equals(user.getPassword())) {
                return ResultTool.error(UserCode.B_USER_2001);
            }

            if (user.getStatus() == StatusEnum.DISABLE.getCode()) {
                return ResultTool.error(UserCode.B_USER_2004);
            }

            Map<String, Object> data = new HashMap<>();
            String token = TokenUtils.getToken(String.valueOf(user.getId()),
                    String.valueOf(user.getMobile()), UserTypeEnum.USER);
            data.put("token", token);
            data.put("userId", user.getId());
            data.put("mobile", user.getMobile());

            // 更新登录日志
            user.setLastLoginIp(NetworkUtil.getIpAddress(request));
            user.setLastLoginTime(DateUtil.nowTimeStamp());

            // 更新用户登录日志
            this.userService.updateUserLoginLog(user);

            return ResultTool.success(data);

        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(e);
        }
    }

    /**
     * 删除用户
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteUser.json", method = RequestMethod.POST)
    public Object deleteUser(HttpServletRequest request) {
        String userId = StringUtils.parseStr(request.getParameter("id"));

        if (StringUtils.isEmpty(userId)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        if (userId.equals("1")) {
            return ResultTool.error(UserCode.B_USER_2006);
        }

        try {

            this.userService.deleteById(StringUtils.parseInt(userId));

            return ResultTool.success();
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    /**
     * 检测用户是否存在
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkUserNameExist.json", method = RequestMethod.POST)
    public Object checkUserNameExist(HttpServletRequest request) {
        String userName = StringUtils
                .parseStr(request.getParameter("userName"));

        if (StringUtils.isEmpty(userName)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            UserEntity entity = this.userService
                    .getUserEntityByUserName(userName);

            if (entity == null) {
                return ResultTool.success();
            }

            return ResultTool.error(UserCode.B_USER_2007);
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    /**
     * 增加用户
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/addUser.json", method = RequestMethod.POST)
    public Object addUser(HttpServletRequest request) {
        String userJsons = StringUtils.parseStr(request.getParameter("user"));

        if (StringUtils.isEmpty(userJsons)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        UserEntity userEntity = JsonUtils.readJson2Entity(userJsons,
                UserEntity.class);

        if (userEntity == null) {
            logger.error("增加用户解析JSON 失败!");
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            if (StringUtils.isEmpty(userEntity.getRealName(),
                    userEntity.getPassword(), userEntity.getTelephone(),
                    userEntity.getUserName())) {

                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            UserEntity tmpEntity = this.userService
                    .getUserEntityByUserName(userEntity.getUserName());

            if (tmpEntity != null) {
                return ResultTool.error(UserCode.B_USER_2007);
            }

            this.userService.addUser(userEntity);

            return ResultTool.success();
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    /**
     * 更改用户状态
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/changeUserStatus.json", method = RequestMethod.POST)
    public Object changeUserStatus(HttpServletRequest request) {
        String userId = StringUtils.parseStr(request.getParameter("id"));
        String status = StringUtils.parseStr(request.getParameter("status"));

        if (StringUtils.isEmpty(userId, status)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            this.userService.changeUserStatus(StringUtils.parseInt(userId),
                    status);

            return ResultTool.success();
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    /**
     * 编辑用户信息
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/editUser.json", method = RequestMethod.POST)
    public Object editUser(HttpServletRequest request) {
        String userJsons = StringUtils.parseStr(request.getParameter("user"));

        if (StringUtils.isEmpty(userJsons)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        UserEntity userEntity = JsonUtils.readJson2Entity(userJsons,
                UserEntity.class);

        if (userEntity == null) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            if (StringUtils.isEmpty(userEntity.getRealName(),
                    userEntity.getUserName(), userEntity.getPassword())) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            if (userEntity.getId() == null || userEntity.getId() == 0) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            UserEntity tmpUserEntity = this.userService
                    .getById(userEntity.getId());
            if (tmpUserEntity == null) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            userEntity.setSalt(tmpUserEntity.getSalt());
            userEntity.setStatus(tmpUserEntity.getStatus());
            userEntity.setCreateTime(tmpUserEntity.getCreateTime());
            userEntity.setLastLoginIp(tmpUserEntity.getLastLoginIp());
            userEntity.setLastLoginTime(tmpUserEntity.getLastLoginTime());
            this.userService.editUser(userEntity);

            return ResultTool.success();
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }
}
